package indi.kider.server.applet.service;

import com.google.gson.Gson;
import indi.kider.common.constant.SmsTemplateCons;
import indi.kider.common.constant.StatusCons;
import indi.kider.common.model.sms.Sms;
import indi.kider.common.model.woniubus.TenantInHouse;
import indi.kider.server.applet.model.User;
import indi.kider.server.sms.mapper.SmsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import pers.vankid.common.constant.HttpCode;
import pers.vankid.common.model.base.CommonResponse;

import java.util.*;

@Service
@SuppressWarnings("all")
public class SmsServiceImpl implements SmsService {

    @Autowired
    private SmsMapper smsMapper;

    @Override
    public CommonResponse tenantSms(TenantInHouse tenantInHouse) throws Exception {
        List<Sms> smsList = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        map.put("companyName", tenantInHouse.getTenantName());
        Sms sms = buildSms(tenantInHouse.getPhone(),map, SmsTemplateCons.TENANT_SMS);
        smsList.add(sms);
        sendSms(smsList);
        return CommonResponse.buildUpdateSuccessResponse("发送成功!",null);
    }

    @Override
    public CommonResponse tenantSuccessSms(TenantInHouse tenantInHouse) throws Exception {
        List<Sms> smsList = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        map.put("houseNum", tenantInHouse.getHouseNum());
        Sms sms = buildSms(tenantInHouse.getPhone(),map,SmsTemplateCons.TENANT_CHECKIN_SMS);
        smsList.add(sms);
        sendSms(smsList);
        return CommonResponse.buildUpdateSuccessResponse("发送成功!",null);
    }

    @Override
    public CommonResponse tenantFailSms(TenantInHouse tenantInHouse) throws Exception {
        List<Sms> smsList = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        map.put("name1", tenantInHouse.getPartName());
        map.put("name2", tenantInHouse.getPartPhone());
        Sms sms = buildSms(tenantInHouse.getPhone(),map,SmsTemplateCons.TENANT_CHECKNOTIN_SMS);
        smsList.add(sms);
        sendSms(smsList);
        return CommonResponse.buildUpdateSuccessResponse("发送成功!",null);
    }

    @Override
    public CommonResponse randomSms(User user) throws Exception {
        List<Sms> smsList = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        map.put("code", user.getRandomNum());
        Sms sms = buildSms(user.getPhone(),map,SmsTemplateCons.RANDOMNUM_SMS);
        smsList.add(sms);
        sendSms(smsList);
        return CommonResponse.buildUpdateSuccessResponse("发送成功!",null);
    }

    /**
     * 组装SMS
     * @param Phones
     * @param map
     * @param templateCode
     * @return
     */
    public Sms buildSms(String Phones,Map<String, String> map,String templateCode){
        Sms sms = new Sms();
        sms.setPhones(Phones);
        sms.setCreateTime(new Date());
        sms.setTemplateCode(templateCode);
        sms.setTemplateContext(SmsTemplateCons.MAP.get(templateCode));
        sms.setSmsContext(new Gson().toJson(map));
        return  sms;
    }

    /**
     * 调用短信服务，处理发送反馈
     * @param smsList
     */
    @Value("${sms.url}")
    private String url;
    private void sendSms(List<Sms>smsList) throws Exception {
        smsList.stream().forEach(sms -> {
            try {
                RestTemplate restTemplate = new RestTemplate();
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
                MultiValueMap<String,String> p = new LinkedMultiValueMap<>();
                p.add("phones",sms.getPhones());
                p.add("type",sms.getType());
                p.add("signType",sms.getSignType());
                p.add("smsContext",sms.getSmsContext());
                p.add("templateCode",sms.getTemplateCode());
                HttpEntity<MultiValueMap<String,String>> entity = new HttpEntity< MultiValueMap<String,String>>(p,headers);
                ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
                CommonResponse response = new Gson().fromJson(responseEntity.getBody(), CommonResponse.class);
                if(response.getStatus().equals(HttpCode.SUCCESS_GET))
                    sms.setState(StatusCons.VALID);
                else
                    sms.setState(StatusCons.HISTORY);
                sms.setResContext(responseEntity.getBody());
            } catch (Exception e) {
                sms.setState(StatusCons.HISTORY);
                sms.setResContext(new Gson().toJson(CommonResponse.buildBadRequestResponse("调用发送服务失败！")));

                e.printStackTrace();
            }finally {
                smsMapper.insert(sms);
            }
        });

    }
}
